package com.beton.api

import BotModel
import com.deepnaming.api.view.configureRouting
import dto.AppConfig
import io.ktor.serialization.kotlinx.json.json
import io.ktor.server.application.install
import io.ktor.server.engine.applicationEngineEnvironment
import io.ktor.server.engine.connector
import io.ktor.server.engine.embeddedServer
import io.ktor.server.netty.Netty
import io.ktor.server.plugins.contentnegotiation.ContentNegotiation
import kotlinx.serialization.json.Json
import org.koin.core.component.KoinComponent
import org.koin.core.component.inject


class KtorServer() : KoinComponent {
    private val appConfig: AppConfig by inject()
    private val botModel: BotModel by inject()

    init {
        val env = applicationEngineEnvironment {
            module {
                configureRouting(
                    botModelImpl = botModel
                )
                install(ContentNegotiation) {
                    json(
                        Json {
                            prettyPrint = true
                            isLenient = true
                            ignoreUnknownKeys = true
                        }
                    )
                }
            }
            connector {
                host = "0.0.0.0"
                port = appConfig.ktorPort.toInt()
            }
        }
        val server = embeddedServer(Netty, env)
        println(server.environment.connectors)
        server.start(true)

    }


    companion object {
        fun createAndStart() {
            KtorServer()
        }
    }
}
